package cn.txy.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Component
public class TokenInterceptor implements RequestInterceptor {

    @Value("sa-token.token-name")
    private String tokenName;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取当前请求
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //得到请求头里面的token
        String tokenValue = requestAttributes.getRequest().getHeader(tokenName);
        //判断token是否为null
        if(StringUtils.isNotEmpty(tokenValue)){
            //有就将token设置到请求头里面
            requestTemplate.header(tokenName,tokenValue);
            log.warn("token转发 - {}" , tokenValue);
        }else{
            log.warn("token转发 - 请求头中并没有Token");
        }

    }
}
